package com.xls.commonlibrary.ad.adn.gm;

import static com.xls.commonlibrary.constant.Const.HYLC_XXL_KP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_KP_TEST_INDEX;

import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationSplashRequestInfo;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;

import io.reactivex.rxjava3.annotations.NonNull;

public class GMSplashUtil {

//    private String mMediaId = "102117864"; // 融合广告位 demo id

    private String mMediaId = ""; // 融合广告位 正式 id


    private String TAG = "GMUtil";

    private static volatile GMSplashUtil singleton = null;

    private GMSplashUtil() {
    }

    public static GMSplashUtil getInstance() {
        if (singleton == null) {
            synchronized (GMSplashUtil.class) {
                if (singleton == null) {
                    singleton = new GMSplashUtil();
                }
            }
        }
        return singleton;
    }


    AppCompatActivity activity;
    ValueCallback<Boolean> valueCallback;
    int delay;

    public void loadSplash(@NonNull AppCompatActivity activity,
                           @NonNull FrameLayout container,
                           @NonNull ValueCallback<Boolean> valueCallback,int delay
    ) {

        this.activity = activity;
        this.valueCallback = valueCallback;
        this.mSplashContainer = container;
        this.delay=delay;
        Logger.d("============广告====开屏====");

        addLifecycle();
        initListeners();


        loadAndShowSplashAd();

    }

    private void callbackSuccess() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(true);
    }

    private void callbackFail() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(false);
    }


    private void addLifecycle() {// 重要
        if (this.activity == null) return;

        this.activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            // 还有很多生命周期都可以感知
            // 这里只关注 onDestroy()的注销ad对象
            @Override
            public void onDestroy(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
//                Logger.d("===========LifecycleOwner=========onDestroy===========");


                /** 6、在onDestroy中销毁广告 */
                if (mCsjSplashAd != null && mCsjSplashAd.getMediationManager() != null) {
                    mCsjSplashAd.getMediationManager().destroy();
                }

            }
        });
    }


    private FrameLayout mSplashContainer;

    private CSJSplashAd mCsjSplashAd;

    private TTAdNative.CSJSplashAdListener mCSJSplashAdListener;
    private CSJSplashAd.SplashAdListener mCSJSplashInteractionListener;


    private void initListeners() {
        this.mCSJSplashAdListener = new TTAdNative.CSJSplashAdListener() {
            @Override
            public void onSplashLoadSuccess(CSJSplashAd csjSplashAd) {
                Log.d(TAG, "splash load success");
            }

            @Override
            public void onSplashLoadFail(CSJAdError csjAdError) {
                Log.d(TAG, "splash load fail, errCode: " + csjAdError.getCode() + ", errMsg: " + csjAdError.getMsg());
//                // splash load fail, errCode: 840040, errMsg: 暂无配置信息，请稍后重试，或者注册config回调，具体参考demo
//
                callbackFail();
            }

            @Override
            public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {
                /** 5、渲染成功后，展示广告 */
                Log.d(TAG, "splash render success");
                mCsjSplashAd = csjSplashAd;
                csjSplashAd.setSplashAdListener(mCSJSplashInteractionListener);
                View splashView = csjSplashAd.getSplashView();
                UIUtils.removeFromParent(splashView);
                mSplashContainer.removeAllViews();
                mSplashContainer.addView(splashView);
            }

            @Override
            public void onSplashRenderFail(CSJSplashAd csjSplashAd, CSJAdError csjAdError) {
                Log.d(TAG, "splash render fail, errCode: " + csjAdError.getCode() + ", errMsg: " + csjAdError.getMsg());
//
                callbackFail();
            }
        };

        // 广告加载监听器
//        this.mCSJSplashAdListener = new TTAdNative.CSJSplashAdListener() {
//            @Override
//            public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {
//                /** 5、渲染成功后，展示广告 */
//                Log.d(TAG, "splash render success");
//                mCsjSplashAd = csjSplashAd;
//                csjSplashAd.setSplashAdListener(mCSJSplashInteractionListener);
//                View splashView = csjSplashAd.getSplashView();
//                UIUtils.removeFromParent(splashView);
//                mSplashContainer.removeAllViews();
//                mSplashContainer.addView(splashView);
//            }
//
//            @Override
//            public void onSplashLoadSuccess() {
//                Log.d(TAG, "splash load success");
//            }
//
//            @Override
//            public void onSplashLoadFail(CSJAdError csjAdError) {
//                Log.d(TAG, "splash load fail, errCode: " + csjAdError.getCode() + ", errMsg: " + csjAdError.getMsg());
//                // splash load fail, errCode: 840040, errMsg: 暂无配置信息，请稍后重试，或者注册config回调，具体参考demo
//
//                callbackFail();
//            }
//
//            @Override
//            public void onSplashRenderFail(CSJSplashAd csjSplashAd, CSJAdError csjAdError) {
//                Log.d(TAG, "splash render fail, errCode: " + csjAdError.getCode() + ", errMsg: " + csjAdError.getMsg());
//
//                callbackFail();
//            }
//        };
        // 广告展示监听器
        this.mCSJSplashInteractionListener = new CSJSplashAd.SplashAdListener() {
            @Override
            public void onSplashAdShow(CSJSplashAd csjSplashAd) {
                Log.d(TAG, "splash show");
            }

            @Override
            public void onSplashAdClick(CSJSplashAd csjSplashAd) {
                Log.d(TAG, "splash click");
            }

            @Override
            public void onSplashAdClose(CSJSplashAd csjSplashAd, int i) {
                Log.d(TAG, "splash close");

                // activity.finish();

                callbackSuccess();


            }
        };
    }

    private void loadAndShowSplashAd() {
        // 设置兜底id
        //第一步、创建开屏自定义兜底对象
        MediationSplashRequestInfo csjSplashRequestInfo = new MediationSplashRequestInfo(
                MediationConstant.ADN_KS,
                BuildConfig.GM_KS_ID,
                BuildConfig.GM_KS_APPID,
                ""
        ) {
        };

        mMediaId = CodeRewardUtil.getInstance().getAdId(HYLC_XXL_KP_TEST, HYLC_XXL_KP_TEST_INDEX);
        Logger.d("============广告====开屏===="+mMediaId);
        /** 1、创建AdSlot对象 */
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mMediaId)
                .setImageAcceptedSize(UIUtils.getScreenWidthInPx(this.activity),
                        UIUtils.getScreenHeightInPx(this.activity))
                .setMediationAdSlot(
                        new MediationAdSlot.Builder()
                                //将自定义兜底对象设置给AdSlot
                                .setMediationSplashRequestInfo(csjSplashRequestInfo)
                                .build())
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this.activity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        /** 4、加载广告 */
        adNativeLoader.loadSplashAd(adSlot, mCSJSplashAdListener,delay);
    }


}
